import { useEffect } from 'react';
import { useState } from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Pie } from '@ant-design/plots';
import { ProCard } from '@ant-design/pro-components';
import { Card, Col, Row, Tooltip } from 'antd';
import dayjs from 'dayjs';

import request from '@/utils/request';
import { fmtLongDate } from '@/utils/time';

import { countList } from './constants';

const pieConfig = {
  angleField: 'value',
  colorField: 'type',
  height: 300,
  appendPadding: 10,
  radius: 0.75,
  legend: false,
  autoFit: false,
  label: {
    type: 'spider',
    labelHeight: 28,
    content: '{name}\n{percentage}',
  },
  interactions: [
    {
      type: 'element-selected',
    },
    {
      type: 'element-active',
    },
  ],
};

const Overall = ({ url }) => {
  const [pieData, setPieData] = useState([]);
  const [countData, setCountData] = useState({});

  useEffect(() => {
    request('/api/overall', {
      method: 'POST',
      data: {
        url,
        date: fmtLongDate(dayjs()),
      },
    }).then(({ data }) => {
      const result = data?.[0] || {};
      const resultPie = [
        {
          type: '无需重构',
          value: result.good_count || 0,
        },
        {
          type: '建议重构',
          value: result.medium_count || 0,
        },
        {
          type: '强烈建议重构',
          value: result.optimize_count || 0,
        },
      ];
      setCountData(result);
      setPieData(resultPie);
    });
  }, [url]);

  return (
    <>
      <ProCard
        title={`当前数据为 ${fmtLongDate(dayjs())}`}
        bodyStyle={{ padding: '80px 0' }}
        ghost
      >
        <Pie data={pieData} {...pieConfig} />
      </ProCard>
      <Row gutter={[16, 24]} wrap>
        {countList.map((item) => (
          <Col span={6} key={item.title}>
            <Card>
              <h3>
                {item.title}
                {item.tip && (
                  <Tooltip title={item.tip}>
                    <QuestionCircleOutlined style={{ marginLeft: '5px' }} />
                  </Tooltip>
                )}
              </h3>
              <span style={{ fontSize: '30px', marginRight: '5px' }}>
                {countData?.[item.field] ?? '-'}
              </span>
              <span>{item.unit || '个'}</span>
            </Card>
          </Col>
        ))}
      </Row>
    </>
  );
};

export default Overall;
